package de.hfu.helper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.StringTokenizer;

import de.hfu.model.DayPlan;
import de.hfu.model.Dish;

public class DataTranslator {
	private static DataTranslator instance = new DataTranslator();

	private static final String BING_URI = "http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=";
	private static final String APP_ID = "6993A87527147BC12455D4D6D90E6333649D0DB8";
	private static String FROM = "de";
	private static String TO = "en";

	private DataTranslator() {

	}

	public static DataTranslator getInstance() {
		return instance;
	}

	private String createRequestURI(String text) {
		return BING_URI + APP_ID + "&text=" + text + "&from=" + FROM + "&to="
				+ TO;
	}

	public String translateFromGermanToEnglish(String text) throws IOException {
		URL url = new URL(createRequestURI(URLEncoder.encode(text, "UTF-8")));
		SimpleXMLParser parser = new SimpleXMLParser(url);
		String result = parser.nextTagContent();
		if (result == null)
			throw new IOException();
		return result;
	}

	public void translateFromGermanToEnglish(DayPlan dayPlan) {
		try {
			// ***** old version: merge all the string then request to server
			// for translation
			// String text = "";
			// for (Dish x : dayPlan.getDishes()) {
			// text += x.getTitle(DataAccess.DEFAULT_LANGUAGE) + " # "
			// + x.getDescription(DataAccess.DEFAULT_LANGUAGE) + " # ";
			// }
			// text = translateFromGermanToEnglish(text);
			// if (text != null) {
			// StringTokenizer stk = new StringTokenizer(text, " # ");
			//
			// for (Dish x : dayPlan.getDishes()) {
			// x.setTitle_en(stk.nextToken());
			// x.setDescription_en(stk.nextToken());
			// }
			// dayPlan.setTranslated(true);
			// }
			
			for (Dish x : dayPlan.getDishes()) {
				x.setTitle_en(translateFromGermanToEnglish(x
						.getTitle(DataAccess.DEFAULT_LANGUAGE)));
				x.setDescription_en(translateFromGermanToEnglish(x
						.getDescription(DataAccess.DEFAULT_LANGUAGE)));
			}
			dayPlan.setTranslated(true);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
